package com.yidaba.database.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

import com.yidaba.database.UserDao;
import com.yidaba.database.pojo.User;

public class UserContentProvider extends ContentProvider {

	public static final String USER_CP="com.yidabanote.USER";
	public static final String USER_ITEMS_TYPE = "vnd.android.cursor.dir/users";
	public static final String USER_ITEM_TYPE = "vnd.android.cursor.item/users";
	//
	private static final UriMatcher sUriMatcher;
	private static final int USER = 1;
	private static final int USER_ID = 2;
	
	UserDao userDao;
	
	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(USER_CP, "users", USER);
		sUriMatcher.addURI(USER_CP, "users/#", USER_ID);
	}
	
	@Override
	public String getType(Uri uri) {
        int match = sUriMatcher.match(uri);
        switch (match)
        {
            case USER:
                return USER_ITEMS_TYPE;
            case USER_ID:
                return USER_ITEM_TYPE;
            default:
                return null;
        }
	}
	
	@Override
	public boolean onCreate() {
		userDao = new UserDao(getContext());
		return false;
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		switch ( sUriMatcher.match(uri)){
		case USER:
			break;
		case USER_ID:
			selection += " "+User._ID+"="+uri.getPathSegments().get(1);
			break;
		}
		if(sortOrder.isEmpty()){
			sortOrder += User._ID+" desc ";
		}
		return userDao.query(User.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		if (sUriMatcher.match(uri) != USER) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		userDao.insert(User.TABLE_NAME, null, values);
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		switch(sUriMatcher.match(uri)){
		case USER:
			return userDao.delete(User.TABLE_NAME, selection, selectionArgs);
		case USER_ID:
			return userDao.delete(User.TABLE_NAME, User._ID+"="+uri.getPathSegments().get(1), null);
		}
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int returnValue = 0;
		switch(sUriMatcher.match(uri)){
		case USER:
			returnValue = userDao.update(User.TABLE_NAME, values, selection, selectionArgs);
			break;
		case USER_ID:
			returnValue = userDao.update(User.TABLE_NAME, values, User._ID+"="+uri.getPathSegments().get(1), null);
			break;
		}
		return returnValue;
	};

}
